package com.zsyh.jiujiu.home;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.zyh.toolslib.base.BaseActivity;
import com.example.zyh.toolslib.utils.EmptyUtil;
import com.example.zyh.toolslib.utils.SPUtils;
import com.example.zyh.toolslib.widget.TitleBar;
import com.google.gson.Gson;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.lwb.retrofit.RetrofitTask;
import com.zsyh.jiujiu.Adress.FabuAdress;
import com.zsyh.jiujiu.Adress.SelectAddresFinish;
import com.zsyh.jiujiu.Api;
import com.zsyh.jiujiu.R;
import com.zsyh.jiujiu.bean.MessageEvn;
import com.zsyh.jiujiu.bean.SucessBean;
import com.zsyh.jiujiu.dialog.ClallBackData;
import com.zsyh.jiujiu.dialog.DanWeiDialog;
import com.zsyh.jiujiu.dialog.TimeSelectDialog;
import com.zsyh.jiujiu.dialog.XianzhiPinDialog;
import com.zsyh.jiujiu.net.MyObserver;
import com.zsyh.jiujiu.utils.CompressPhotoUtils;
import com.zsyh.jiujiu.utils.GlideEngine;
import com.zsyh.jiujiu.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

/**
 * @ProjectName: livvehelp
 * @Package: com.zsyh.lsb.ui
 * @ClassName:
 * @Description: java类作用描述
 * @Author: zsyh
 * @CreateDate: 2020/9/7 11:59
 * @UpdateUser: liangwanbo
 * @UpdateDate: 2020/9/7 11:59
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class FaBuActivity extends BaseActivity implements AMapLocationListener {

    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.company)
    TextView company;
    @BindView(R.id.people)
    TextView people;
    @BindView(R.id.biaotitle)
    EditText biaotitle;
    @BindView(R.id.desc)
    EditText desc;
    @BindView(R.id.imagelist)
    RecyclerView imagelist;
    @BindView(R.id.xinpin)
    TextView xinpin;
    @BindView(R.id.rexinpin)
    RelativeLayout rexinpin;
    @BindView(R.id.classtype)
    TextView classtype;
    @BindView(R.id.reclassty)
    RelativeLayout reclassty;
    @BindView(R.id.tvnum)
    TextView tvnum;
    @BindView(R.id.number)
    EditText number;
    @BindView(R.id.tvstorenum)
    TextView tvstorenum;
    @BindView(R.id.storenumber)
    EditText storenumber;
    @BindView(R.id.zhibaotime)
    TextView zhibaotime;
    @BindView(R.id.rezhibao)
    RelativeLayout rezhibao;
    @BindView(R.id.shencangtime)
    TextView shencangtime;
    @BindView(R.id.resheengchan)
    RelativeLayout resheengchan;
    @BindView(R.id.unit)
    TextView unit;
    @BindView(R.id.reunit)
    RelativeLayout reunit;
    @BindView(R.id.tvprivice)
    TextView tvprivice;
    @BindView(R.id.money)
    EditText money;
    @BindView(R.id.diqu)
    TextView diqu;
    @BindView(R.id.rediqu)
    RelativeLayout rediqu;
    @BindView(R.id.redingwei)
    RelativeLayout redingwei;
    @BindView(R.id.xuqiou)
    TextView xuqiou;
    @BindView(R.id.rexuqiou)
    RelativeLayout rexuqiou;
    @BindView(R.id.huangougood)
    EditText huangougood;
    @BindView(R.id.fabu)
    TextView fabu;
    @BindView(R.id.imageweizhi)
    ImageView imageweizhi;
    @BindView(R.id.dingwei)
    TextView dingwei;
    private BaseQuickAdapter<String, BaseViewHolder> mAdapter;
    List<String> Imagelist = new ArrayList<>();
    private String isNewGoods;
    private String goodsClass, goodsClassTwo, goodsClassThree;
    private final static int REQUESTCODE = 1; // 返回的结果码
    private String shelfLife, produntDate, goodsUnit, releaseProv, releaseProvname, releaseCity, releaseCityname;
    //声明mlocationClient对象
    private AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    private AMapLocationClientOption mLocationOption = null;
    private String clatype, exchangeClass, userType, lat, lon;
    private String goodid, goodsTitle, goodsPic, goodsDesc, beginCount, stockCount, goodsPrice, currentAddress, exchangeGoods;

    private String httpurl;
    @Override
    protected int initLayout() {
        return R.layout.activity_fabu;
    }

    @Override
    protected void initView() {
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new MessageEvn("home", "home"));
                thisActivity.finish();
            }
        });
        titleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                thisActivity.finish();
            }
        });
        Imagelist.add("");
        mAdapter = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_imageselect, Imagelist) {
            @Override
            protected void convert(@NonNull BaseViewHolder helper, String item) {
                if (EmptyUtil.isEmpty(item)) {
                    helper.setVisible(R.id.add, true);
                    helper.setVisible(R.id.reuimage, false);
                } else {
                    helper.setVisible(R.id.add, false);
                    helper.setVisible(R.id.reuimage, true);
                    Glide.with(thisActivity).load(item).into(helper.<ImageView>getView(R.id.image));
                }
                helper.setOnClickListener(R.id.delete, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Imagelist.remove(helper.getPosition());
                        mAdapter.notifyDataSetChanged();
                    }
                });

                helper.setOnClickListener(R.id.add, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        EasyPhotos.createAlbum(thisActivity, true, GlideEngine.getInstance())
                                .setFileProviderAuthority("com.zsyh.jiujiu.fileprovider")
                                .setCount(22)
                                .start(new SelectCallback() {
                                    @Override
                                    public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                                        if (Imagelist.size() == 1) {
                                            Imagelist.clear();
                                        } else {
                                            Imagelist.remove(Imagelist.size() - 1);
                                        }
                                        for (int i = 0; i < photos.size(); i++) {
                                            Imagelist.add(photos.get(i).path);
                                        }
                                        Imagelist.add("");
                                        mAdapter.notifyDataSetChanged();

                                    }
                                });
                    }
                });

            }
        };
        imagelist.setLayoutManager(new GridLayoutManager(thisActivity, 4));
        imagelist.setAdapter(mAdapter);
    }

    @Override
    protected void initData() {
        goodid = getIntent().getStringExtra("goodid");
        if (EmptyUtil.isEmpty(goodid)) {
            userType = "个人";
        } else {
            userType = getIntent().getStringExtra("userType");
        }

        goodsTitle = getIntent().getStringExtra("goodsTitle");
        biaotitle.setText(goodsTitle);
        goodsDesc = getIntent().getStringExtra("goodsDesc");
        desc.setText(goodsDesc);
        goodsPic = getIntent().getStringExtra("goodsPic");
        if(!EmptyUtil.isEmpty(goodsPic)){
            String[] split = goodsPic.split("\\|");
            if(Imagelist!=null){
                Imagelist.clear();
            }
            for(int i=0;i<split.length;i++){
                Imagelist.add(split[i]);
            }
            Imagelist.add("");
        }
        mAdapter.notifyDataSetChanged();
        isNewGoods = getIntent().getStringExtra("isNewGoods");
        xinpin.setText(isNewGoods);
        goodsClass = getIntent().getStringExtra("goodsClass");
        goodsClassTwo = getIntent().getStringExtra("goodsClassTwo");
        goodsClassThree = getIntent().getStringExtra("goodsClassThree");
        beginCount = getIntent().getStringExtra("beginCount");
        number.setText(beginCount);
        stockCount = getIntent().getStringExtra("stockCount");
        storenumber.setText(stockCount);
        shelfLife = getIntent().getStringExtra("shelfLife");
        zhibaotime.setText(shelfLife);
        produntDate = getIntent().getStringExtra("produntDate");
        shencangtime.setText(produntDate);
        goodsUnit = getIntent().getStringExtra("goodsUnit");
        unit.setText(goodsUnit);
        goodsPrice = getIntent().getStringExtra("goodsPrice");
        money.setText(goodsPrice);
        releaseProv = getIntent().getStringExtra("releaseProv");

        releaseProvname = getIntent().getStringExtra("releaseProvname");
        releaseCity = getIntent().getStringExtra("releaseCity");
        releaseCityname = getIntent().getStringExtra("releaseCityname");
        diqu.setText(releaseProvname + releaseCityname );
        currentAddress = getIntent().getStringExtra("currentAddress");
        dingwei.setText(currentAddress);
        exchangeClass = getIntent().getStringExtra("exchangeClass");
        xuqiou.setText(exchangeClass);
        exchangeGoods = getIntent().getStringExtra("exchangeGoods");
        huangougood.setText(exchangeGoods);
        lat = getIntent().getStringExtra("lat");
        lon = getIntent().getStringExtra("lon");
    }

    @Override
    protected void initEvent() {

    }

    @OnClick({R.id.company, R.id.people, R.id.rexinpin, R.id.reclassty, R.id.rezhibao, R.id.resheengchan, R.id.reunit, R.id.rediqu, R.id.redingwei, R.id.rexuqiou, R.id.fabu})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.company:
                people.setTextColor(getResources().getColor(R.color.color_gray_999999));
                company.setTextColor(getResources().getColor(R.color.white));
                people.setBackgroundResource(R.mipmap.ic_huizuo);
                company.setBackgroundResource(R.mipmap.ic_hongyou);
                userType = "企业";
                break;
            case R.id.people:
                people.setTextColor(getResources().getColor(R.color.white));
                company.setTextColor(getResources().getColor(R.color.color_gray_999999));
                people.setBackgroundResource(R.mipmap.ic_hongzuo);
                company.setBackgroundResource(R.mipmap.ic_huiyou);
                userType = "个人";
                break;
            case R.id.rexinpin:
                XianzhiPinDialog xianzhiPinDialog = new XianzhiPinDialog();
                xianzhiPinDialog.setSelectAddresFinish(new ClallBackData() {
                    @Override
                    public void getData(String data, String name, String number) {
                        isNewGoods = data;
                        xinpin.setText(data);
                    }
                });
                xianzhiPinDialog.show(getSupportFragmentManager(), "");
                break;
            case R.id.reclassty:
                clatype = "1";
                Intent intent = new Intent(this, ClassFicationActivity.class);
                startActivityForResult(intent, REQUESTCODE);

                break;
            case R.id.rezhibao:
                TimeSelectDialog timeSelectDialog = new TimeSelectDialog(true);
                timeSelectDialog.setSelectAddresFinish(new ClallBackData() {
                    @Override
                    public void getData(String data, String name, String number) {
                        zhibaotime.setText(data);
                        shelfLife = data;
                    }
                });
                timeSelectDialog.show(getSupportFragmentManager(), "");
                break;
            case R.id.resheengchan:
                TimeSelectDialog timeSelectDialogshenchan = new TimeSelectDialog(true);
                timeSelectDialogshenchan.setSelectAddresFinish(new ClallBackData() {
                    @Override
                    public void getData(String data, String name, String number) {
                        shencangtime.setText(data);
                        produntDate = data;
                    }
                });
                timeSelectDialogshenchan.show(getSupportFragmentManager(), "");
                break;
            case R.id.reunit:
                DanWeiDialog xianzhiPinDialogunit = new DanWeiDialog();
                xianzhiPinDialogunit.setSelectAddresFinish(new ClallBackData() {
                    @Override
                    public void getData(String data, String name, String number) {
                        unit.setText(name);
                        goodsUnit = data;
                    }
                });
                xianzhiPinDialogunit.show(getSupportFragmentManager(), "");
                break;
            case R.id.rediqu:
                FabuAdress pop = new FabuAdress(this);
                pop.setSelectAddresFinish(new SelectAddresFinish() {
                    @Override
                    public void finish(String provinceCode, String cityCode, String areaCode, String provincename, String cityname, String areaname) {
                        releaseProv = provinceCode;
                        releaseCity = cityCode;
                        releaseProvname = provincename;
                        releaseCityname = cityname;

                        diqu.setText(provincename + cityname + areaname);
                    }
                });
                pop.show(getFragmentManager(), "address");

                break;
            case R.id.redingwei:
                startLoc();
                break;
            case R.id.rexuqiou:
                clatype = "2";
                Intent intentxuqiong = new Intent(this, ClassFicationActivity.class);
                startActivityForResult(intentxuqiong, REQUESTCODE);
                break;
            case R.id.fabu:
                if (EmptyUtil.isEmpty(biaotitle.getText().toString())) {
                    ToastUtils.showShort(thisActivity, "请输入标题");
                    return;
                }
                if (EmptyUtil.isEmpty(desc.getText().toString())) {
                    ToastUtils.showShort(thisActivity, "请输入内容描述");
                    return;
                }


                if (Imagelist.size() == 0) {
                    ToastUtils.showShort(thisActivity, "请上传图片");
                    return;
                }
                if (EmptyUtil.isEmpty(isNewGoods)) {
                    ToastUtils.showShort(thisActivity, "请选择新品/闲置");
                    return;
                }

                if (EmptyUtil.isEmpty(goodsClassThree)) {
                    ToastUtils.showShort(thisActivity, "请选择分类");
                    return;
                }

                if (EmptyUtil.isEmpty(number.getText().toString())) {
                    ToastUtils.showShort(thisActivity, "请输入商品的起换数量");
                    return;
                }

                if (EmptyUtil.isEmpty(storenumber.getText().toString())) {
                    ToastUtils.showShort(thisActivity, "请输入商品库存的数量");
                    return;
                }

                if (EmptyUtil.isEmpty(shelfLife)) {
                    ToastUtils.showShort(thisActivity, "请选择保质期");
                    return;
                }

                if (EmptyUtil.isEmpty(produntDate)) {
                    ToastUtils.showShort(thisActivity, "请选择生产日期");
                    return;
                }

                if (EmptyUtil.isEmpty(goodsUnit)) {
                    ToastUtils.showShort(thisActivity, "请选择单位");
                    return;
                }

                if (EmptyUtil.isEmpty(money.getText().toString())) {
                    ToastUtils.showShort(thisActivity, "请输入价格");
                    return;
                }

                if (EmptyUtil.isEmpty(releaseCity)) {
                    ToastUtils.showShort(thisActivity, "请选择地区");
                    return;
                }

                if (EmptyUtil.isEmpty(releaseCity)) {
                    ToastUtils.showShort(thisActivity, "请选择地区");
                    return;
                }

                if (EmptyUtil.isEmpty(dingwei.getText().toString())) {
                    ToastUtils.showShort(thisActivity, "请点击定位当前位置");
                    return;
                }

                if (EmptyUtil.isEmpty(exchangeClass)) {
                    ToastUtils.showShort(thisActivity, "请选择交换需求");
                    return;
                }

                if (EmptyUtil.isEmpty(huangougood.getText().toString())) {
                    ToastUtils.showShort(thisActivity, "请输入您想要换的商品");
                    return;
                }
                Imagelist.remove(Imagelist.size() - 1);
                if(EmptyUtil.isEmpty(goodsPic)){
                    UpImage(Imagelist);
                }else{
                    httpurl="";
                    List<String> list=new ArrayList<>();
                    for(int i=0;i<Imagelist.size();i++){
                        if(Imagelist.get(i).contains("http")){
                            httpurl=httpurl+Imagelist.get(i)+"|";
                        }else{
                            list.add(Imagelist.get(i));
                        }
                    }
                    UpImage(list);
                }




                break;
        }
    }

    /**
     * 發佈產品
     */
    public void fabu(String userId,
                     String userType,
                     String goodsTitle,
                     String goodsDesc,
                     String goodsPic,
                     String isNewGoods,
                     String goodsClass,
                     String goodsClassTwo,
                     String goodsClassThree,
                     String beginCount,
                     String stockCount,
                     String shelfLife,
                     String produntDate,
                     String goodsUnit,
                     String goodsPrice,
                     String releaseProv,
                     String releaseProvname,
                     String releaseCity,
                     String releaseCityname,
                     String currentAddress,
                     String exchangeClass,
                     String exchangeGoods,
                     String lat,
                     String lon) {


        RetrofitTask.getInstance()
                .createApi(Api.class)
                .saveGoods(userId,
                        userType,
                        goodsTitle,
                        goodsDesc,
                        goodsPic,
                        isNewGoods,
                        goodsClass,
                        goodsClassTwo,
                        goodsClassThree,
                        beginCount,
                        stockCount,
                        shelfLife,
                        produntDate,
                        goodsUnit,
                        goodsPrice,
                        releaseProv,
                        releaseProvname,
                        releaseCity,
                        releaseCityname,
                        currentAddress,
                        exchangeClass,
                        exchangeGoods,
                        lat,
                        lon)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new MyObserver(this, true) {
                    @Override
                    protected void onError(String errorMsg) {

                    }

                    @Override
                    protected void onSuccess(String JsonStr) {
                        Gson gson = new Gson();
                        SucessBean sucessBean = gson.fromJson(JsonStr, SucessBean.class);
                        if (sucessBean.getCode() == 0) {
                            thisActivity.finish();
                        }

                    }
                });

    }

    /**
     * 编辑
     *
     * @param
     * @param
     * @param
     */

    public void bianjigood(String id,
                           String userId,
                           String userType,
                           String goodsTitle,
                           String goodsDesc,
                           String goodsPic,
                           String isNewGoods,
                           String goodsClass,
                           String goodsClassTwo,
                           String goodsClassThree,
                           String beginCount,
                           String stockCount,
                           String shelfLife,
                           String produntDate,
                           String goodsUnit,
                           String goodsPrice,
                           String releaseProv,
                           String releaseProvname,
                           String releaseCity,
                           String releaseCityname,
                           String currentAddress,
                           String exchangeClass,
                           String exchangeGoods,
                           String lat,
                           String lon) {


        RetrofitTask.getInstance()
                .createApi(Api.class)
                .updateGoods(id,
                        userId,
                        userType,
                        goodsTitle,
                        goodsDesc,
                        goodsPic,
                        isNewGoods,
                        goodsClass,
                        goodsClassTwo,
                        goodsClassThree,
                        beginCount,
                        stockCount,
                        shelfLife,
                        produntDate,
                        goodsUnit,
                        goodsPrice,
                        releaseProv,
                        releaseProvname,
                        releaseCity,
                        releaseCityname,
                        currentAddress,
                        exchangeClass,
                        exchangeGoods,
                        lat,
                        lon)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new MyObserver(this, true) {
                    @Override
                    protected void onError(String errorMsg) {

                    }

                    @Override
                    protected void onSuccess(String JsonStr) {
                        Gson gson = new Gson();
                        SucessBean sucessBean = gson.fromJson(JsonStr, SucessBean.class);
                        if (sucessBean.getCode() == 0) {
                            thisActivity.finish();
                        }

                    }
                });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 2) {
            if (requestCode == REQUESTCODE) {
                String yijiname = data.getStringExtra("yijiname");
                String erjiname = data.getStringExtra("erjiname");
                String sanjiname = data.getStringExtra("sanjiname");
                if (clatype.equals("1")) {
                    goodsClass = data.getStringExtra("yiid");
                    goodsClassTwo = data.getStringExtra("erid");
                    goodsClassThree = data.getStringExtra("sanid");
                    classtype.setText(yijiname + "/" + erjiname + "/" + sanjiname);
                } else if (clatype.equals("2")) {
                    exchangeClass = sanjiname;
                    xuqiou.setText(sanjiname);
                }


            }
        }
    }


    private void startLoc() {
        mlocationClient = new AMapLocationClient(thisActivity);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mlocationClient.setLocationListener(this);
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setOnceLocation(true);
        mLocationOption.setOnceLocationLatest(true);
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        //启动定位
        mlocationClient.startLocation();
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                double latitude = amapLocation.getLatitude();
                double longitude = amapLocation.getLongitude();
                lat = amapLocation.getLatitude() + "";
                lon = amapLocation.getLongitude() + "";
                String city = amapLocation.getCity();
                String citycode = amapLocation.getAdCode();
                Log.e("dingwei", city + citycode + latitude + longitude + amapLocation.toStr() + "");
                SPUtils.put(thisActivity, "cityname", city);
                SPUtils.put(thisActivity, "citycode", citycode);
                SPUtils.put(thisActivity, "lat", latitude + "");
                SPUtils.put(thisActivity, "lon", longitude + "");
                dingwei.setText(amapLocation.getDistrict() + amapLocation.getStreet());

            } else {
                com.blankj.utilcode.util.ToastUtils.showShort("定位失败，请重新进入");
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());

            }
        }
    }

    public void UpImage(List<String> list) {
        new CompressPhotoUtils().CompressPhoto(this, list, new CompressPhotoUtils.CompressCallBack() {
            @Override
            public void success(List<String> list) {
                MultipartBody.Builder builder = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM);//表单类型
                //多张图片
                for (int i = 0; i < list.size(); i++) {
                    File file = new File(list.get(i));//filePath 图片地址
                    RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                    builder.addFormDataPart("file", file.getName(), imageBody);//"imgfile"+i 后台接收图片流的参数名
                }
                List<MultipartBody.Part> parts = builder.build().parts();
                RetrofitTask.getInstance()
                        .createApi(Api.class)
                        .upload(parts)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeOn(Schedulers.io())
                        .subscribe(new Observer<ResponseBody>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(ResponseBody responseBody) {
                                try {
                                    String body = responseBody.string();
                                    JSONArray jsonArray = new JSONArray(body);
                                    String imageurl = "";
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                                        if (i == jsonArray.length() - 1) {
                                            imageurl = imageurl + jsonObject.getString("url");
                                        } else {
                                            imageurl = imageurl + jsonObject.getString("url") + "|";
                                        }
                                    }

                                    if (EmptyUtil.isEmpty(goodid)) {
                                        fabu((String) SPUtils.get(thisActivity, "userid", ""),
                                                userType,
                                                biaotitle.getText().toString(),
                                                desc.getText().toString(),
                                                imageurl,
                                                isNewGoods,
                                                goodsClass,
                                                goodsClassTwo,
                                                goodsClassThree,
                                                number.getText().toString(),
                                                storenumber.getText().toString(),
                                                shelfLife,
                                                produntDate,
                                                goodsUnit,
                                                money.getText().toString(),
                                                releaseProv,
                                                releaseProvname,
                                                releaseCity,
                                                releaseCityname,
                                                dingwei.getText().toString(),
                                                exchangeClass,
                                                huangougood.getText().toString(),
                                                lat,
                                                lon);
                                    } else {
                                        String imurl=httpurl+imageurl;
                                        bianjigood(goodid, (String) SPUtils.get(thisActivity, "userid", ""),
                                                userType,
                                                biaotitle.getText().toString(),
                                                desc.getText().toString(),
                                                imurl,
                                                isNewGoods,
                                                goodsClass,
                                                goodsClassTwo,
                                                goodsClassThree,
                                                number.getText().toString(),
                                                storenumber.getText().toString(),
                                                shelfLife,
                                                produntDate,
                                                goodsUnit,
                                                money.getText().toString(),
                                                releaseProv,
                                                releaseProvname,
                                                releaseCity,
                                                releaseCityname,
                                                dingwei.getText().toString(),
                                                exchangeClass,
                                                huangougood.getText().toString(),
                                                lat,
                                                lon);
                                    }


                                    Log.e("body", body + "");
                                } catch (IOException e) {
                                    e.printStackTrace();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onComplete() {

                            }
                        });

            }
        });
    }
}
